﻿using My.Admin.Dto.User;
using My.Admin.Model.System;
using My.Admin.Service.System.IService;
using SqlSugar.IOC;

namespace My.Admin.Service.System
{
	/// <summary>
	/// 系统用户角色服务
	/// </summary>
	public class SysUserRoleService :  BaseService<SysUserRole>, ISysUserRoleService
	{
		//private readonly SysCacheService _sysCacheService;

		public SysUserRoleService()
		{
		}

		/// <summary>
		/// 授权用户角色
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task GrantUserRole(UserRoleInput input)
		{
			await DeleteAsync(u => u.UserId == input.UserId);

			if (input.RoleIdList == null || input.RoleIdList.Count < 1) return;
			var roles = input.RoleIdList.Select(u => new SysUserRole
			{
				UserId = input.UserId,
				RoleId = u
			}).ToList();
			await InsertRangeAsync(roles);
			//_sysCacheService.Remove(CacheConst.KeyUserButton + input.UserId);
		}

		/// <summary>
		/// 根据角色Id删除用户角色
		/// </summary>
		/// <param name="roleId"></param>
		/// <returns></returns>
		public async Task DeleteUserRoleByRoleId(long roleId)
		{
			await AsQueryable()
				 .Where(u => u.RoleId == roleId)
				 .Select(u => u.UserId)
				 .ForEachAsync(userId =>
				 {
					 //_sysCacheService.Remove(CacheConst.KeyUserButton + userId);
				 });

			await DeleteAsync(u => u.RoleId == roleId);
		}

		/// <summary>
		/// 根据用户Id删除用户角色
		/// </summary>
		/// <param name="userId"></param>
		/// <returns></returns>
		public async Task DeleteUserRoleByUserId(long userId)
		{
			await DeleteAsync(u => u.UserId == userId);
			//_sysCacheService.Remove(CacheConst.KeyUserButton + userId);
		}

		/// <summary>
		/// 根据用户Id获取角色集合
		/// </summary>
		/// <param name="userId"></param>
		/// <returns></returns>
		public async Task<List<SysRole>> GetUserRoleList(long userId)
		{
			var sysUserRoleList = await AsQueryable()
				.Mapper(u => u.SysRole, u => u.RoleId)
				.Where(u => u.UserId == userId).ToListAsync();
			return sysUserRoleList.Where(u => u.SysRole != null).Select(u => u.SysRole).ToList();
		}

		/// <summary>
		/// 根据用户Id获取角色Id集合
		/// </summary>
		/// <param name="userId"></param>
		/// <returns></returns>
		public async Task<List<long>> GetUserRoleIdList(long userId)
		{
			return await AsQueryable()
				.Where(u => u.UserId == userId).Select(u => u.RoleId).ToListAsync();
		}

		/// <summary>
		/// 根据角色Id获取用户Id集合
		/// </summary>
		/// <param name="roleId"></param>
		/// <returns></returns>
		public async Task<List<long>> GetUserIdList(long roleId)
		{
			return await AsQueryable()
				.Where(u => u.RoleId == roleId).Select(u => u.UserId).ToListAsync();
		}
	}
}
